package xx.iverson.school_manage.send;

import com.zhenzi.sms.ZhenziSmsClient;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * xx.iverson.school_manage.send.SendSms
 * 发送短信
 * on 2024/10/16
 *
 * @author weijx
 */
public class SendSms {
    public static String send(String phone,String templateId,String code) throws Exception {
        ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "109491", "ZjZmMmUyZTktZGI0Yi00ZmY5LTkzOWItN2M3YjZlNmQ1NDgy");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phone);
        params.put("templateId", templateId);
        String[] templateParams = new String[1];
        templateParams[0] = code;
        params.put("templateParams", templateParams);
        return extractDataField(client.send(params));
    }

    public static String extractDataField(String json) {
        // 找到"data"字段的开始位置
        int start = json.indexOf("\"data\":\"") + 8; // 8 是 "\"data\":\"".length()

        // 找到"data"字段值的结束位置
        int end = json.indexOf("\"", start);
        if (end == -1) {
            return null; // 如果找不到结束引号，返回null
        }

        // 提取"data"字段的值
        return json.substring(start, end);
    }

    public static String generateCaptcha(int length) {
        // 创建一个Random对象
        Random random = new Random();

        // 构建一个StringBuilder来存储生成的验证码
        StringBuilder captchaBuilder = new StringBuilder();

        // 循环生成指定长度的随机数字
        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10); // 生成0-9之间的随机数字
            captchaBuilder.append(digit);
        }

        // 返回生成的验证码
        return captchaBuilder.toString();
    }
}
